<template>
  <div>
    <el-form :inline="true" style="margin:10px 0">
      <el-button v-for="(operate, index) in formData.operateList" :key="index" 
      v-if="operate.place=='header'" 
      @click="operateAction(operate)" 
      :type="operate.buttonType"
      size="small"
      >{{operate.name}}</el-button>
      <template>
        <slot name="operateHeader"></slot>
      </template>
    </el-form>
    <!-- 导入数据对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :data = "upload.data"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-button type="primary" @click="exportTemplate" size="mini">下载模板</el-button>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { operateActionPost } from '@/api/interface/operate.js'
  import { operateAction } from '@/views/interface/form/operate.js'
  import { Loading } from 'element-ui'
  import { getToken } from '@/utils/auth'
  import cript from '@/utils/encript.js'
  export default {
    components: {},
    props: {
      multipleSelection: {
        type: Array,
        default: ()=>[]
      },
      formData: {
        type: Object,
        default: ()=>{}
      }
    },
    data() {
      return {
        fullscreenLoading: null,
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: '',
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: 'token ' + getToken()},
          // 上传的地址
          url: '',
          data: {}
        },    
      }
    },
    created() {
    },
    methods: {
      operateAction(operate){
        console.log('操作', operate)
        var params = {}
        var rowIds = []
        if(operate.beforeTypes == 'single'){
          if(this.multipleSelection.length==0){
            this.$message({
              message: '请选择操作行！',
              type: 'info'
            })
            return 
          }else if(this.multipleSelection.length>1){
            this.$message({
              message: '只能选择单行！',
              type: 'info'
            })
            return 
          }
          
        }else if(operate.beforeTypes == 'multiple'){
          if(this.multipleSelection.length<=0){
            this.$message({
              message: '请选择操作行！',
              type: 'info'
            })
            return 
          }
        }
        this.multipleSelection.map((item)=>{
          rowIds.push(item.id)
        })
        params.obj_ids = rowIds
        if(operate.types == 'system'){
          switch (operate.key) {
            case 'create':
                this.$router.push({name: 'Update', query: { formData: encodeURIComponent(JSON.stringify(this.formData))}})
              break;
            case 'delete':
              var _this = this
              this.$confirm('是否确认删除选中的' + rowIds.length + '条记录?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
              }).then(function(){
                return operateActionPost(operate.formModel.url + operate.key + 'Action/', params).then((res) => {
                  if(res.data.code == 10000){
                    _this.$message({
                        message: res.data.data,
                        type: 'success'
                      })
                      _this.$emit('refreshItemList')
                  }
                })
              })
              break;
            case 'export':
              params.formId = this.formData.formModel.id
              this.fullscreenLoading = Loading.service({ fullscreen: true, text: '数据正在加工中，请稍后！' })
              operateActionPost(operate.formModel.url + operate.key + 'Action/', params).then((res) => {
                if(res.data.code == 10000){
                  this.$message({
                      message: '操作成功',
                      type: 'success'
                    })
                    this.fullscreenLoading.close()
                    window.location.href = res.data.data
                }
              })
              break;
            case 'import':
              this.upload.title = '导入数据'
              this.upload.url = this.formData.formModel.url + 'importExcel' + 'Action/'
              this.upload.open = true
              this.upload.data = {'formId': this.formData.formModel.id}
              break;
            default:
                break;
          }
        }else{
          this.$emit('operateAction', operate, rowIds)
        }
        // this.$emit('operateAction', operate)
      },
      /** 下载模板操作 */
      exportTemplate() {
        this.fullscreenLoading = Loading.service({ fullscreen: true, text: '数据正在加工中，请稍后！' })
        operateActionPost(this.formData.formModel.url + 'exportTemplate' + 'Action/', {formId: this.formData.formModel.id}).then((res) => {
          if(res.data.code == 10000){
              this.fullscreenLoading.close()
              window.location.href = res.data.data
          }
        })
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit()
      },
      // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      if(response.code == 10001){
        var data = {'data': response}
        var res = cript.decript(data)
        this.$alert('成功导入' + res.data.successCount + '条数据', '导入结果', { dangerouslyUseHTMLString: true })
        this.$emit('refreshItemList')
      }if(response.code == 8888){
        Message({
          message: response.message,
          duration: 5 * 1000
        })
      }
    },
    }
  }

</script>
